import Foundation

class ChewDataService {
    static let shared = ChewDataService()
    
    private init() {}
    
    /// 保存咀嚼数据到服务器
    /// - Parameters:
    ///   - scenario: 场景名称（如：硬质食物、软质食物等）
    ///   - note: 备注（吃的什么或“没咀嚼”）
    ///   - userName: 用户名
    ///   - duration: 录制时长（秒）
    ///   - rawCsvUrl: 原始数据 CSV 文件的 OSS 链接
    ///   - timestamp: 可选的时间戳，用于保证数据库记录的时间顺序
    ///   - sessionUUID: 可选的会话UUID，用于标识同一组数据（自由记录场景使用）
    func saveChewData(
        scenario: String,
        note: String,
        userName: String,
        duration: Double,
        rawCsvUrl: String,
        timestamp: Date? = nil,
        sessionUUID: String? = nil
    ) async throws {
        let urlString = "\(AppConfig.serverBaseURL)\(AppConfig.saveChewDataEndpoint)"
        guard let url = URL(string: urlString) else {
            throw NetworkError.invalidURL
        }
        
        // 构建请求参数
        let timestampToUse = timestamp ?? Date()
        var parameters: [String: Any] = [
            "scenario": scenario,
            "note": note,
            "user_name": userName,
            "duration_sec": duration,
            "raw_csv_url": rawCsvUrl,
            "timestamp": ISO8601DateFormatter().string(from: timestampToUse)
        ]
        
        // 如果有 sessionUUID，添加到参数中
        if let uuid = sessionUUID {
            parameters["uuid"] = uuid
        }
        
        // 创建请求
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
        request.timeoutInterval = 30
        
        // 发送请求
        let (data, response) = try await URLSession.shared.data(for: request)
        
        guard let httpResponse = response as? HTTPURLResponse else {
            throw NetworkError.invalidResponse
        }
        
        guard (200...299).contains(httpResponse.statusCode) else {
            // 尝试解析错误信息
            if let errorDict = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
               let message = errorDict["message"] as? String {
                throw NetworkError.serverError(message: message, statusCode: httpResponse.statusCode)
            }
            throw NetworkError.serverError(message: "请求失败", statusCode: httpResponse.statusCode)
        }
    }
}

// MARK: - 错误类型
enum NetworkError: LocalizedError {
    case invalidURL
    case invalidResponse
    case serverError(message: String, statusCode: Int)
    
    var errorDescription: String? {
        switch self {
        case .invalidURL:
            return "无效的服务器地址"
        case .invalidResponse:
            return "无效的服务器响应"
        case .serverError(let message, let statusCode):
            return "服务器错误 (\(statusCode)): \(message)"
        }
    }
}
